package com.center.mapperscan;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

/**
 * @Author dzl
 * @Date 2022/1/20 10:20 上午
 * 用于进行扫描实现
 */
public class MyMapperScanConfig implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware {
    /**
     * 要扫描的包
     */
    private String scanBasePackages;

    private ApplicationContext context;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        String[] packages = StringUtils.commaDelimitedListToStringArray(scanBasePackages);
        if (packages.length == 0) {
            /*扫描启动包*/
            String[] beanNames = context.getBeanNamesForAnnotation(SpringBootApplication.class);
            Object bean = context.getBean(beanNames[0]);
            SpringBootApplication springBootApplication = AnnotationUtils.findAnnotation(bean.getClass(), SpringBootApplication.class);
            assert springBootApplication != null;
            String[] basePackages = springBootApplication.scanBasePackages();
            if (basePackages.length == 0) {
                String springBootPackage = ClassUtils.getPackageName(bean.getClass().getName());
                packages = new String[]{springBootPackage};
            } else {
                packages = basePackages;
            }
        }
        MyMapperClassScanner scanner = new MyMapperClassScanner(beanDefinitionRegistry, false);
        /*进行扫描*/
        scanner.doScan(packages);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}
